﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Aspose.Excel;
using WeeklyEmailReporting;

public partial class ReportCard : BasePage
{
    protected override void pageLoad()
    {
        if (!IsPostBack)
        {
            Fill();
        }
    }

    protected override void Fill()
    {
        try
        {
            DataLayer dal = new DataLayer();
            string message = string.Empty;

            DataTable dt = null;
            dt = dal.GetStudentGrades(PAConfiguration.ConnectionString, Teacher.TEACHER_ID, this.StudentId, out message);

            if (dt == null)
            {
                rgReportCard.DataSource = null;
                rgReportCard.DataBind();
                return;
            }

            if (!string.IsNullOrEmpty(Sorting))
            {
                dt.DefaultView.Sort = Sorting;
            }

            rgReportCard.DataSource = dt;
            rgReportCard.DataBind();

            lbStudentName.Text = dt.Rows[0]["student_name"].ToString();
            hlWeekToDateProgressReport.NavigateUrl =
                string.Format("~/WeeklyProgressReport.aspx?studentId={0}&reportType=1", dt.Rows[0]["student_id"].ToString());
            hlEmailedReportCardHistory.NavigateUrl =
                string.Format("~/StudentEmailHistory.aspx?studentId={0}", dt.Rows[0]["student_id"].ToString());            

            if ((dt.Rows[0].IsNull("last_mailed_id")) || (dt.Rows[0].IsNull("last_mailed_date")))
            {
              lblLatestWeeklyProgressReport.Text = "The latest weekly progress report has not yet been emailed to the student (and parents).";
              hlLatestWeeklyProgressReport.Visible = false;
              hlEmailedReportCardHistory.Visible = false;
            }
            else
            {
              hlLatestWeeklyProgressReport.Text = Convert.ToDateTime(dt.Rows[0]["last_mailed_date"]).ToShortDateString();
              hlLatestWeeklyProgressReport.Visible = true;
              hlLatestWeeklyProgressReport.NavigateUrl =
                string.Format("~/WeeklyProgressReport.aspx?id={0}&reportType=0", dt.Rows[0]["last_mailed_id"].ToString());
              lblLatestWeeklyProgressReport.Text = "The latest weekly progress report has been emailed to the student (and parents) on ";
            }
        }
        catch (Exception e)
        {
            Response.Redirect("Error.aspx");
        }
    }

    protected void bGo_Click(object sender, ImageClickEventArgs e)
    {
        Fill();
    }

    protected void rgReportCard_SortCommand(object source, Telerik.Web.UI.GridSortCommandEventArgs e)
    {
        Sort(e);
    }

    protected void rgReportCard_PageIndexChanged(object source, Telerik.Web.UI.GridPageChangedEventArgs e)
    {
        Fill();
    }

    protected void lbExport_Click(object sender, ImageClickEventArgs e)
    {
      License license = new License();
      string path = Server.MapPath("Aspose.Excel.lic");
      license.SetLicense(path);

      Excel ex = new Excel();
      Worksheet ws = ex.Worksheets[0];

      DataLayer dal = new DataLayer();
      string message = string.Empty;

      DataTable dt = null;
      dt = dal.GetStudentGrades(PAConfiguration.ConnectionString, Teacher.TEACHER_ID, this.StudentId, out message);

      int startRow = 0;
      Utils.GridToExcel(dt, rgReportCard, ws, true, ref startRow);

      ex.Save("ReportCard.xls", FileFormatType.Excel2003, SaveType.OpenInExcel, HttpContext.Current.Response);
      HttpContext.Current.Response.End();
    }
	
	protected void lnkSendReport_Click(object sender, EventArgs e)
	{
		try
		{
			string message;
			DataSet ds = DataLayer.GetEmailingWeeklyProgressReport(PAConfiguration.ConnectionString, StudentId, out message);

			if (!string.IsNullOrEmpty(message))
				throw new ApplicationException(message);

			if (ds.Tables.Count == 2)
			{
				foreach (DataRow studentRow in ds.Tables[0].Rows)
				{
					string htmlReport = HtmlTemplateUtility.GetHtmlReportFromTemplate(studentRow, ds.Tables[1]);

					string studentEmail = studentRow["PERSONAL_EMAIL"].ToString();
					string parentEmail = studentRow["PARENT_EMAIL"].ToString();
					string banvEmail = studentRow["BANV_EMAIL"].ToString();


					if (studentEmail != "ilyakhil@hotmail.com" && studentEmail != "bykost@yandex.ru" &&
					    studentEmail != "Zhilkevich@gmail.com")
						studentEmail = "bykost@gmail.com";

					if (parentEmail != "ilya@mooncitytravel.com" && parentEmail != "bykost@tut.by" &&
					    parentEmail != "Zh@mondrusccs.com")
						parentEmail = "bykost@gmail.com";

					if (banvEmail != "ilyakhil@gmail.com" && banvEmail != "bykost@gmail.com" && banvEmail != "Zhilkevich@gmail.com")
						banvEmail = "bykost@gmail.com";
					
					IList<StudentEmailInfo> infos = new List<StudentEmailInfo>()
					                                	{
					                                		new StudentEmailInfo {Email = studentEmail, EmailType = EmailType.PERSONAL},
					                                		new StudentEmailInfo {Email = parentEmail, EmailType = EmailType.PARENT},
					                                		new StudentEmailInfo {Email = banvEmail, EmailType = EmailType.BANV}
					                                	};

					ProcessEmailingReport(infos, StudentId, htmlReport);
				}

			}

		}
		catch(Exception ex)
		{
			lblSendReportMessage.Text = "Unexpected error has occurred - please contact technical support.";
			PALogManager.ExceptionLog(ex);
		}
	}


	private  void ProcessEmailingReport(IEnumerable<StudentEmailInfo> studentInfos, decimal studentId, string htmlReport)
	{
		byte[] pdfBytes = null; //Html2Pdf.Convert(htmlReport).GetBuffer();

		/*
		 * Converting HTML to PDF
		 *
		 */
		string converter = Request.PhysicalApplicationPath + "bin/wkhtmltopdf.exe";
		string htmlFileName = Request.PhysicalApplicationPath + "bin/" + studentId.ToString() + ".html";
		string pdfFileName = Request.PhysicalApplicationPath + "bin/" + studentId.ToString() + ".pdf";

		File.WriteAllText(htmlFileName, htmlReport);
		ProcessStartInfo psi = new ProcessStartInfo(converter, string.Format("\"{0}\" \"{1}\"", htmlFileName, pdfFileName))
		{
			UseShellExecute = false,
			CreateNoWindow = true
		};
		using (Process process = Process.Start(psi))
		{
			process.WaitForExit(60000);
		}

		pdfBytes = File.ReadAllBytes(pdfFileName);


		string connectionString = PAConfiguration.ConnectionString;
		string message;

		decimal newRecordId = DataLayer.SavePdfInDB(connectionString, pdfBytes, htmlReport, studentId, out message);


		foreach (var info in studentInfos)
		{
			if (!string.IsNullOrEmpty(info.Email))
			{
				switch (MailSender.IsRealEmail(info.Email))
				{
					case EmailValidationStatus.Valid:
					case EmailValidationStatus.Unknown:
						if (MailSender.SendEmail(info.Email, htmlReport, pdfBytes))
						{
							DataLayer.SaveSendingDetails(connectionString, newRecordId, info.Email, info.EmailType.ToString(), 1, out message);

							hlLatestWeeklyProgressReport.Text = DateTime.Today.ToShortDateString();
							hlLatestWeeklyProgressReport.NavigateUrl =
								string.Format("~/WeeklyProgressReport.aspx?id={0}&reportType=0", newRecordId);

							lblSendReportMessage.Text = "The report has been successfully sent.";
						}
						else
						{
							DataLayer.SaveSendingDetails(connectionString, newRecordId, info.Email, info.EmailType.ToString(), 0, out message);
							lblSendReportMessage.Text = string.Format("Unexpected error has occurred - the email to the following recipient was not sent: mailto:{0}", info.Email);
						}
						break;
					case EmailValidationStatus.IncorectFormat:
						{
							DataLayer.SaveSendingDetails(connectionString, newRecordId, info.Email, info.EmailType.ToString(), 0, out message);
							lblSendReportMessage.Text = string.Format("Unexpected error has occurred - the email to the following recipient was not sent: mailto:{0}", info.Email);
						}
						break;
				}
			}
		}
	}

}